package tool

import (
	"context"
	"time"

	"github.com/fatih/color"
	"github.com/go-redis/redis/v8"
)

const CAPTCHA = "captcha:"

type RedisStore struct {
	Redis *redis.Client
}

// 存储的是 "8926" 而不是 8926，需要转换一下
func (r RedisStore) Set(id string, value string) error {
	// v, _ := strconv.Atoi(value)
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	k := CAPTCHA + id
	err := r.Redis.Set(ctx, k, value, 300*time.Second).Err()
	if err != nil {
		panic(err)
	}
	return nil
}

func (r RedisStore) Get(id string, clear bool) string {
	key := CAPTCHA + id
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	color.Red("key=%v", key)
	color.Red("ctx=%v", ctx)
	color.Red("Redis=%v", r.Redis)
	re, err := r.Redis.Get(ctx, key).Result()
	if err != nil {
		color.Red("err=%v", err)
		return ""
	}

	if clear {
		r.Redis.Del(ctx, key)
	}

	// return string(re.Value)
	return re
}

func (r RedisStore) Verify(id, answer string, clear bool) bool {
	v := r.Get(id, clear)
	return v == answer
}
